package com.javasm.controller.MisMannageController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author:JAVASM
 * @description:
 * @date:2022/5/22 13:29
 * @version:0.1
 * @since:jdk11
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //得到用户输入的请求路径
        String requestURI = req.getRequestURI();
        //根据用户输入的请求路径,拆分出想要执行的方法名
        String methodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);

        try {
            //根据方法名得出想要执行的方法对象
            Method declaredMethod = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            //执行对应的方法
            declaredMethod.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            //异常信息由tomcat报错
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
